const express = require('express');
const jwt = require('jsonwebtoken');
const cors = require('cors');
const app = express();
const PORT = 3000;

// 中间件
app.use(cors());
app.use(express.json());

// 密钥，实际应用中应该放在环境变量中
const SECRET_KEY = 'your-secret-key';
const REFRESH_SECRET_KEY = 'your-refresh-secret-key';

// 模拟用户数据
const users = [
  {
    id: 1,
    username: 'admin',
    password: 'password'
  }
];

// 模拟refresh token存储
const refreshTokens = [];

// 登录接口
app.post('/api/login', (req, res) => {
  const { username, password } = req.body;

  // 查找用户
  const user = users.find(u => u.username === username && u.password === password);

  if (!user) {
    return res.status(401).json({ message: '用户名或密码错误' });
  }

  // 生成token
  const token = jwt.sign(
    { userId: user.id, username: user.username },
    SECRET_KEY,
    { expiresIn: '10s' } // token有效期10秒
  );

  // 生成refresh token
  const refreshToken = jwt.sign(
    { userId: user.id, username: user.username },
    REFRESH_SECRET_KEY,
    { expiresIn: '7d' } // refresh token有效期7天
  );

  // 存储refresh token
  refreshTokens.push(refreshToken);

  res.json({ token, refreshToken });
});

// 刷新token接口
app.post('/api/refresh', (req, res) => {
  const { refreshToken } = req.body;

  // 检查refresh token是否存在
  if (!refreshToken || !refreshTokens.includes(refreshToken)) {
    return res.status(403).json({ message: '无效的refresh token' });
  }

  try {
    // 验证refresh token
    const decoded = jwt.verify(refreshToken, REFRESH_SECRET_KEY);

    // 生成新的token
    const newToken = jwt.sign(
      { userId: decoded.userId, username: decoded.username },
      SECRET_KEY,
      { expiresIn: '10s' }
    );

    // 生成新的refresh token
    const newRefreshToken = jwt.sign(
      { userId: decoded.userId, username: decoded.username },
      REFRESH_SECRET_KEY,
      { expiresIn: '7d' }
    );

    // 更新refresh token列表
    const index = refreshTokens.indexOf(refreshToken);
    if (index !== -1) {
      refreshTokens.splice(index, 1);
    }
    refreshTokens.push(newRefreshToken);

    res.json({ token: newToken, refreshToken: newRefreshToken });
  } catch (error) {
    return res.status(403).json({ message: '无效的refresh token' });
  }
});

// 测试接口，需要验证token
app.get('/api/test', authenticateToken, (req, res) => {
  res.json({
    // message: '请求成功',
    data: {
      userId: req.user.userId,
      username: req.user.username,
      timestamp: new Date().toISOString()
    }
  });
});

// 登出接口
app.post('/api/logout', (req, res) => {
  const { refreshToken } = req.body;
  if (refreshToken) {
    const index = refreshTokens.indexOf(refreshToken);
    if (index !== -1) {
      refreshTokens.splice(index, 1);
    }
  }
  res.json({ message: '登出成功' });
});

// token验证中间件
function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader && authHeader.split(' ')[1];

  if (!token) {
    return res.status(401).json({ message: '未提供token' });
  }

  try {
    const decoded = jwt.verify(token, SECRET_KEY);
    req.user = decoded;
    next();
  } catch (error) {
    // token过期
    if (error.name === 'TokenExpiredError') {
      return res.status(401).json({ message: 'token已过期' });
    }
    return res.status(403).json({ message: '无效的token' });
  }
}

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});